/*
 * VersionResource.cpp
 *
 *  Created on: 2013. 11. 26.
 *      Author: mega
 */

#include "VersionResource.h"
#include <Database/Static.h>
#include "../macro.h"

namespace ProjectZ { namespace NResource {

VersionResource::VersionResource()
{

}

VersionResource::~VersionResource()
{
	clsVersionTree.clear();
}

bool
VersionResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT NATIONAL_CODE, COMPANY, VERSION FROM resource_version WHERE IS_ALLOW = 1");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	clsVersionTree.clear();

	while (clsAuto->Next())
	{
		Toolkit::Str<3> NATIONAL_CODE;
		int company;
		int version;

		clsAuto->GetRecord() >> NATIONAL_CODE >> company >> version;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsVersionTree[company].push_back(version);
	}

	return true;
}

bool
VersionResource::IsAllowConnection(int company, int requestVersion)
{
	auto iter = clsVersionTree.find(company);
	if (iter == clsVersionTree.end())
		return false;

	VERSIONVECTOR & _versionVector = clsVersionTree[company];

	for (int i = 0; i < static_cast<int>(_versionVector.size()); i++)
	{
		if (_versionVector[i] == requestVersion)
			return true;
	}

	return false;
}


} /*NResource*/ } /*ProjectZ*/
